// video-detail.js
const { videoAPI } = require('../../interface.js')

Page({
  data: {
    currentIndex: 0,
    showTopTip: false,
    showBottomTip: false,
    // 音量控制相关
    showVolumeIndicator: false,
    volumePercent: 100,
    // 静音状态
    isMuted: false,
    // 进度条相关

    // 原始视频列表
    originalVideoList: [
    ],
    // 混合视频列表（包含广告）
    videoList: [],
    // 待播放视频队列
    playQueue: [],
    // 动态视频队列（最多3个，最少2个）
    dynamicQueue: [],
    // 当前视频上下文
    currentVideoContext: null,
    // 触摸相关
    touchStartY: 0,
    touchStartX: 0,
    // 视频时长缓存

    // 激励视频广告
    rewardedVideoAd: null,
    // 是否已观看广告
    hasWatchedAd: false,
    // 待播放的视频索引
    pendingPlayIndex: -1,
    // 滑动计数器
    swipeCount: 0
  },

  onLoad(options) {
    // 保存传入的视频ID，用于后续定位
    this.targetVideoId = options.id

    // 先生成混合视频列表（使用本地数据）
    // this.generateMixedVideoList()

    // 获取所有视频数据（异步加载API数据）
    this.getAllVideos()

    // this.loadMoreVideos()

    // 初始化待播放队列
    this.initPlayQueue()

    // 初始化激励视频广告
    this.initRewardedVideoAd()

    // 为当前视频创建上下文
    const currentVideoContext = wx.createVideoContext(`video-${this.data.currentIndex}`, this)
    this.setData({ currentVideoContext })

    // 获取当前视频时长
    // this.getVideoDuration(currentVideoContext, this.data.currentIndex)

    this.initAd()
    // 延迟播放当前视频，确保页面渲染完成
    setTimeout(() => {
      this.playCurrentVideo()
    }, 500)
  },// 初始化广告
  initAd() {
    // 若在开发者工具中无法预览广告，请切换开发者工具中的基础库版本
    // 在页面中定义插屏广告
    let interstitialAd = null

    // 在页面onLoad回调事件中创建插屏广告实例
    if (wx.createInterstitialAd) {
      interstitialAd = wx.createInterstitialAd({
        adUnitId: 'adunit-33b827f858676232'
      })
      interstitialAd.onLoad(() => { })
      interstitialAd.onError((err) => {
        console.error('插屏广告加载失败', err)
      })
      interstitialAd.onClose(() => { })
    }

    // 在适合的场景显示插屏广告
    if (interstitialAd) {
      interstitialAd.show().catch((err) => {
        console.error('插屏广告显示失败', err)
      })
    }
  },
  onAdplay() {
    console.log('视频贴片广告 播放开始')
  },
  onAdload() {
    console.log('视频贴片广告 加载成功')
  },
  onAdclose() {
    console.log('视频贴片广告 关闭成功')
  },
  onAdError(err) {
    console.error('视频贴片广告 加载失败', err)
  },
  // 获取所有视频数据
  getAllVideos() {
    wx.showLoading({
      title: '加载视频数据...'
    })

    videoAPI.getVideoList(1, 10000)
      .then(res => {
        if (res.code === 200 && res.data && res.data.videos) {
          // 将API返回的视频数据映射为标准格式

          res.data.videos.forEach(video => {
            console.log(video)
          })
          const apiVideos = res.data.videos.map(video => ({
            id: video.id,
            title: video.title || '未知标题',
            videoUrl: video?.file?.oss_url || '',
            currentSrc: '', // 用于懒加载的当前src
            isLoading: false, // 视频加载状态
            description: video.description || '暂无描述',
            adUnitId: 'adunit-e48c178fe28c318e' || '',
            isPlaying: false,
            author_nickname: video.author_nickname || '未知用户',
            author_avatar: video.author_avatar || { oss_url: '/images/placeholder.png' },
            isFollowed: false,
            isMuted: false
          }))
          console.log(apiVideos)
          // 直接用API数据替换原始视频列表
          this.setData({
            originalVideoList: apiVideos
          })

          // 重新生成混合视频列表
          this.generateMixedVideoList()

          // 如果有目标视频ID，定位到对应的视频
          if (this.targetVideoId) {
            const index = this.data.videoList.findIndex(video => video.id == this.targetVideoId)
            if (index !== -1) {
              console.log(`找到目标视频，索引: ${index}, 视频ID: ${this.targetVideoId}`)
              this.setData({ currentIndex: index })

              // 更新视频上下文
              const currentVideoContext = wx.createVideoContext(`video-${index}`, this)
              this.setData({ currentVideoContext })
            } else {
              console.log(`未找到目标视频，视频ID: ${this.targetVideoId}`)
            }
          }

          // 初始化视频懒加载状态
          this.initVideoLazyLoad()

          // 重新初始化播放队列
          this.initPlayQueue()

          // 更新播放队列
          this.updatePlayQueue(this.data.videoList)

          // 重新初始化动态队列
          this.initDynamicQueue()

          // 初始化关注状态
          this.initFollowStatus()

          console.log('视频数据加载完成，总计视频数量:', this.data.originalVideoList.length)
        }
        wx.hideLoading()
      })
      .catch(err => {
        console.error('获取视频数据失败:', err)
        wx.hideLoading()
        wx.showToast({
          title: '加载视频数据失败',
          icon: 'none'
        })
      })
  },

  // 初始化视频懒加载状态
  initVideoLazyLoad() {
    const currentIndex = this.data.currentIndex
    const videoList = this.data.videoList.map((video, index) => {
      const shouldLoadSrc = index === currentIndex && !video.isLoading && video.currentSrc !== video.videoUrl
      return {
        ...video,
        currentSrc: shouldLoadSrc ? video.videoUrl : (index === currentIndex ? video.currentSrc : ''),
        isLoading: shouldLoadSrc ? true : video.isLoading
      }
    })
    
    // 只在有变化时才更新
    const hasChanges = videoList.some((video, index) => {
      const originalVideo = this.data.videoList[index]
      return video.currentSrc !== originalVideo.currentSrc || video.isLoading !== originalVideo.isLoading
    })
    
    if (hasChanges) {
      this.setData({ videoList })
      console.log('视频懒加载初始化完成，当前视频索引:', currentIndex)
    }
  },

  // 初始化激励视频广告
  initRewardedVideoAd() {
    // 创建激励视频广告实例
    // 官方文档: https://developers.weixin.qq.com/miniprogram/dev/api/ad/wx.createRewardedVideoAd.html
    if (wx.createRewardedVideoAd) {
      this.data.rewardedVideoAd = wx.createRewardedVideoAd({
        adUnitId: 'adunit-rewardvideo-test' // 测试广告位ID
      })

      // 监听广告关闭事件
      // 官方文档: https://developers.weixin.qq.com/miniprogram/dev/api/ad/RewardedVideoAd.onClose.html
      this.data.rewardedVideoAd.onClose((res) => {
        const currentVideo = this.data.videoList[this.data.currentIndex]

        if (res && res.isEnded) {
          // 用户看完了广告
          console.log('广告播放完成')

          if (currentVideo && currentVideo.type === 'ad') {
            // 如果当前是广告项，跳转到下一个视频
            this.skipAdAndContinue(this.data.currentIndex)
          } else {
            // 如果是普通视频前的广告，播放视频
            this.setData({ hasWatchedAd: true })
            if (this.data.pendingPlayIndex !== -1) {
              this.playVideoAfterAd(this.data.pendingPlayIndex)
              this.setData({ pendingPlayIndex: -1 })
            }
          }
        } else {
          // 用户中途关闭了广告
          if (currentVideo && currentVideo.type === 'ad') {
            // 如果是广告项，提示并跳过
            // 官方文档: https://developers.weixin.qq.com/miniprogram/dev/api/ui/interaction/wx.showToast.html
            wx.showToast({
              title: '广告已跳过',
              icon: 'none'
            })
            this.skipAdAndContinue(this.data.currentIndex)
          } else {
            // 如果是普通视频前的广告，提示观看完整广告
            // 官方文档: https://developers.weixin.qq.com/miniprogram/dev/api/ui/interaction/wx.showToast.html
            wx.showToast({
              title: '请观看完整广告后播放视频',
              icon: 'none'
            })
          }
        }
      })

      // 监听广告加载失败
      // 官方文档: https://developers.weixin.qq.com/miniprogram/dev/api/ad/RewardedVideoAd.onError.html
      this.data.rewardedVideoAd.onError((err) => {
        console.log('激励视频广告加载失败', err)
        const currentVideo = this.data.videoList[this.data.currentIndex]

        if (currentVideo && currentVideo.type === 'ad') {
          // 如果是广告项，跳过
          this.skipAdAndContinue(this.data.currentIndex)
        } else {
          // 如果是普通视频前的广告，直接播放视频
          this.setData({ hasWatchedAd: true })
          if (this.data.pendingPlayIndex !== -1) {
            this.playVideoAfterAd(this.data.pendingPlayIndex)
            this.setData({ pendingPlayIndex: -1 })
          }
        }
      })
    }
  },

  // 生成混合视频列表（每5个视频插入一个广告）
  generateMixedVideoList() {
    const mixedList = [...this.data.originalVideoList]

    // 为普通视频随机添加广告属性，大概两个视频中加一个
    mixedList.forEach((video, index) => {
      // 随机决定是否添加广告属性，概率约为50%
      if (Math.random() < 0.5) {
        video.hasAd = true
      }
    })

    // 每5个视频插入一个广告
    for (let i = 4; i < mixedList.length; i += 6) {
      const adItem = {
        id: `ad_${Date.now()}_${Math.random()}`,
        title: '精彩内容即将呈现',
        videoUrl: '', // 广告没有视频URL
        cover: 'https://via.placeholder.com/750x1334/ff9500/ffffff?text=广告',
        author: '赞助商',
        authorAvatar: 'https://via.placeholder.com/80x80/ff9500/ffffff?text=广告',
        description: '观看广告支持我们继续创作优质内容',
        category: '广告',
        duration: '广告',
        isPlaying: false,
        type: 'ad',
        isMuted: false
      }
      mixedList.splice(i + 1, 0, adItem)
    }

    this.setData({
      videoList: mixedList
    })
  },

  // 初始化播放队列
  initPlayQueue() {
    const playQueue = this.data.videoList.map((video, index) => ({
      ...video,
      index: index,
      status: index === this.data.currentIndex ? 'current' : 'waiting'
    }))

    this.setData({ playQueue })

    // 初始化动态队列
    this.initDynamicQueue()
  },

  // 初始化动态队列
  initDynamicQueue() {
    const currentIndex = this.data.currentIndex
    const videoList = this.data.videoList
    const dynamicQueue = []

    // 添加前一个视频（如果存在）
    if (currentIndex > 0) {
      dynamicQueue.push({
        ...videoList[currentIndex - 1],
        queuePosition: 'previous',
        originalIndex: currentIndex - 1
      })
    }

    // 添加当前视频
    dynamicQueue.push({
      ...videoList[currentIndex],
      queuePosition: 'current',
      originalIndex: currentIndex
    })

    // 添加下一个视频（如果存在）
    if (currentIndex < videoList.length - 1) {
      dynamicQueue.push({
        ...videoList[currentIndex + 1],
        queuePosition: 'next',
        originalIndex: currentIndex + 1
      })
    }

    this.setData({ dynamicQueue })
    console.log('动态队列初始化完成:', dynamicQueue.map(v => `${v.queuePosition}: ${v.title}`))
  },

  // 更新动态队列
  updateDynamicQueue(newCurrentIndex, direction = 'next') {
    const videoList = this.data.videoList
    const dynamicQueue = []

    // 添加前一个视频（如果存在）
    if (newCurrentIndex > 0) {
      dynamicQueue.push({
        ...videoList[newCurrentIndex - 1],
        queuePosition: 'previous',
        originalIndex: newCurrentIndex - 1
      })
    }

    // 添加当前视频
    dynamicQueue.push({
      ...videoList[newCurrentIndex],
      queuePosition: 'current',
      originalIndex: newCurrentIndex
    })

    // 添加下一个视频（如果存在）
    if (newCurrentIndex < videoList.length - 1) {
      dynamicQueue.push({
        ...videoList[newCurrentIndex + 1],
        queuePosition: 'next',
        originalIndex: newCurrentIndex + 1
      })
    }

    this.setData({ dynamicQueue })
    console.log(`动态队列更新完成 (${direction}):`, dynamicQueue.map(v => `${v.queuePosition}: ${v.title}`))
  },

  // 获取动态队列信息
  getDynamicQueueInfo() {
    const queue = this.data.dynamicQueue
    return {
      length: queue.length,
      previous: queue.find(v => v.queuePosition === 'previous'),
      current: queue.find(v => v.queuePosition === 'current'),
      next: queue.find(v => v.queuePosition === 'next'),
      queue: queue
    }
  },

  // 根据队列位置获取视频
  getVideoByQueuePosition(position) {
    return this.data.dynamicQueue.find(v => v.queuePosition === position)
  },

  // 滑动切换视频
  onSwiperChange(e) {
    const newIndex = e.detail.current
    const oldIndex = this.data.currentIndex
    const currentVideo = this.data.videoList[newIndex]

    // 检查是否到达顶部
    if (newIndex === 0 && oldIndex > 0) {
      this.showTopTip()
    }

    // 检查是否到达底部
    if (newIndex === this.data.videoList.length - 1 && oldIndex < this.data.videoList.length - 1) {
      this.showBottomTip()
    }

    // 停止之前的视频
    this.stopVideo(oldIndex)

    // 如果当前是广告项，显示激励视频广告
    if (currentVideo && currentVideo.type === 'ad') {
      this.showAdBeforePlay(newIndex)
      return
    }

    // 立即创建新视频的上下文
    const videoContext = wx.createVideoContext(`video-${newIndex}`, this)

    // 检查是否需要更新currentSrc，避免重复赋值
    const needsUpdate = this.data.videoList.some((video, index) => {
      if (index === newIndex) {
        return video.currentSrc !== video.videoUrl || !video.isPlaying || video.isLoading
      }
      return video.currentSrc !== '' || video.isPlaying || video.isLoading
    })

    let videoList = this.data.videoList
    if (needsUpdate) {
      // 只在需要时更新videoList
      videoList = this.data.videoList.map((video, index) => {
        if (index === newIndex) {
          const shouldSetSrc = video.currentSrc !== video.videoUrl && !video.isLoading
          return {
            ...video,
            progressPercent: 0,
            currentTime: '00:00',
            totalTime: '00:00',
            isPlaying: true,
            currentSrc: shouldSetSrc ? video.videoUrl : video.currentSrc,
            isLoading: shouldSetSrc ? true : false // 设置加载状态
          }
        }
        return {
          ...video,
          isPlaying: false,
          currentSrc: video.currentSrc !== '' ? '' : video.currentSrc, // 只在需要时清空
          isLoading: false // 非当前视频重置加载状态
        }
      })
    }

    // 更新当前索引和视频上下文，重置广告观看状态
    const updateData = {
      currentIndex: newIndex,
      currentVideoContext: videoContext,
      hasWatchedAd: true // 设置为true，跳过广告直接播放
    }
    
    // 只在videoList发生变化时才更新
    if (needsUpdate) {
      updateData.videoList = videoList
    }
    
    this.setData(updateData)

    // 立即播放新视频，不等待广告逻辑
    setTimeout(() => {
      if (videoContext) {
        videoContext.play()
      }
    }, 100)

    // 更新播放队列状态
    this.updatePlayQueueStatus(newIndex, oldIndex)

    // 更新动态队列
    const direction = newIndex > oldIndex ? 'next' : 'previous'
    this.updateDynamicQueue(newIndex, direction)

    // 当滑动到倒数第二个视频时，加载更多视频
    // if (newIndex >= this.data.videoList.length - 2) {
    //   this.loadMoreVideos()
    // }
  },

  // 显示顶部提示
  showTopTip() {
    this.setData({ showTopTip: true })
    setTimeout(() => {
      this.setData({ showTopTip: false })
    }, 2000)
  },

  // 显示底部提示
  showBottomTip() {
    this.setData({ showBottomTip: true })
    setTimeout(() => {
      this.setData({ showBottomTip: false })
    }, 2000)
  },

  // 播放当前视频
  playCurrentVideo() {
    const currentIndex = this.data.currentIndex

    // 检查是否需要观看广告（每次播放新视频时）
    if (!this.data.hasWatchedAd) {
      this.showAdBeforePlay(currentIndex)
      return
    }

    this.playVideoAfterAd(currentIndex)
  },

  // 显示广告后播放视频
  showAdBeforePlay(index) {
    return;
    const currentVideo = this.data.videoList[index]

    // 如果是广告项，显示激励视频广告
    if (currentVideo && currentVideo.type === 'ad') {
      if (this.data.rewardedVideoAd) {
        // 显示激励视频广告
        // 官方文档: https://developers.weixin.qq.com/miniprogram/dev/api/ad/RewardedVideoAd.show.html
        this.data.rewardedVideoAd.show().catch(() => {
          // 广告显示失败，重新加载
          // 官方文档: https://developers.weixin.qq.com/miniprogram/dev/api/ad/RewardedVideoAd.load.html
          this.data.rewardedVideoAd.load().then(() => {
            return this.data.rewardedVideoAd.show()
          }).catch(() => {
            // 重新加载也失败，跳过广告
            console.log('广告显示失败，跳过广告')
            this.skipAdAndContinue(index)
          })
        })
      } else {
        // 没有广告实例，跳过广告
        this.skipAdAndContinue(index)
      }
    } else {
      // 普通视频，设置待播放索引
      this.setData({ pendingPlayIndex: index })

      if (this.data.rewardedVideoAd) {
        // 显示激励视频广告
        // 官方文档: https://developers.weixin.qq.com/miniprogram/dev/api/ad/RewardedVideoAd.show.html
        this.data.rewardedVideoAd.show().catch(() => {
          // 广告显示失败，重新加载
          // 官方文档: https://developers.weixin.qq.com/miniprogram/dev/api/ad/RewardedVideoAd.load.html
          this.data.rewardedVideoAd.load().then(() => {
            return this.data.rewardedVideoAd.show()
          }).catch(err => {
            console.log('激励视频广告显示失败', err)
            // 广告失败时直接播放视频
            this.setData({ hasWatchedAd: true })
            this.playVideoAfterAd(index)
          })
        })
      } else {
        // 没有广告时直接播放
        this.setData({ hasWatchedAd: true })
        this.playVideoAfterAd(index)
      }
    }
  },

  // 跳过广告并继续
  skipAdAndContinue(index) {
    // 官方文档: https://developers.weixin.qq.com/miniprogram/dev/api/ui/interaction/wx.showToast.html
    wx.showToast({
      title: '广告加载失败，已跳过',
      icon: 'none',
      duration: 1500
    })

    // 自动跳转到下一个视频
    const nextIndex = index + 1
    if (nextIndex < this.data.videoList.length) {
      this.setData({ currentIndex: nextIndex })
      // 如果下一个也是广告，继续跳过
      const nextVideo = this.data.videoList[nextIndex]
      if (nextVideo && nextVideo.type === 'ad') {
        this.skipAdAndContinue(nextIndex)
      } else {
        // 播放下一个正常视频
        this.playVideoAfterAd(nextIndex)
      }
    }
  },

  // 播放广告后的视频
  playVideoAfterAd(index) {
    // 创建视频上下文对象
    // 官方文档: https://developers.weixin.qq.com/miniprogram/dev/api/media/video/wx.createVideoContext.html
    const videoContext = wx.createVideoContext(`video-${index}`, this)

    if (videoContext) {
      videoContext.play()

      // 检查是否需要更新播放状态
      const currentVideo = this.data.videoList[index]
      const needsUpdate = !currentVideo.isPlaying
      
      if (needsUpdate) {
        // 更新视频播放状态
        const videoList = this.data.videoList.map((video, idx) => ({
          ...video,
          isPlaying: idx === index
        }))

        this.setData({
          videoList,
          currentVideoContext: videoContext
        })
      } else {
        // 只更新视频上下文
        this.setData({
          currentVideoContext: videoContext
        })
      }
    }
  },

  // 停止指定视频
  stopVideo(index) {
    if (index >= 0 && index < this.data.videoList.length) {
      const videoContext = wx.createVideoContext(`video-${index}`, this)
      if (videoContext) {
        videoContext.pause()
        videoContext.seek(0) // 重置到开头
      }

      // 更新视频播放状态
      const videoList = this.data.videoList.map((video, idx) => ({
        ...video,
        isPlaying: idx === index ? false : video.isPlaying
      }))

      this.setData({ videoList })
    }
  },

  // 更新播放队列状态
  updatePlayQueueStatus(newIndex, oldIndex) {
    const playQueue = this.data.playQueue.map((item, index) => {
      let status = 'waiting'
      if (index === newIndex) {
        status = 'current'
      } else if (index < newIndex) {
        status = 'played'
      }
      return { ...item, status }
    })

    this.setData({ playQueue })
  },

  // 更新播放队列
  updatePlayQueue(videoList) {
    const playQueue = videoList.map((video, index) => {
      let status = 'waiting';
      if (index === this.data.currentIndex) {
        status = 'current';
      } else if (index < this.data.currentIndex) {
        status = 'played';
      }
      return {
        ...video,
        index: index,
        status: status
      };
    });

    this.setData({ playQueue });
  },

  // 视频点击事件
  onVideoTap(e) {
    const index = e.currentTarget.dataset.index
    const currentVideo = this.data.videoList[index]
    const videoContext = wx.createVideoContext(`video-${index}`, this)

    if (videoContext) {
      if (currentVideo.isPlaying) {
        // 当前正在播放，点击暂停
        videoContext.pause()
      } else {
        // 当前暂停，点击播放
        videoContext.play()
      }
    }
  },

  // 视频播放事件
  onVideoPlay(e) {
    const index = e.currentTarget.dataset.index

    // 创建并保存当前视频上下文
    const videoContext = wx.createVideoContext(`video-${index}`, this)

    // 获取视频时长
    // this.getVideoDuration(videoContext, index)

    // 检查是否需要更新播放状态
    const currentVideo = this.data.videoList[index]
    const needsUpdate = !currentVideo.isPlaying || currentVideo.isLoading
    
    if (needsUpdate) {
      // 只更新播放状态，重置加载状态
      const videoList = this.data.videoList.map((video, idx) => ({
        ...video,
        isPlaying: idx === index,
        isLoading: idx === index ? false : video.isLoading // 播放开始时重置加载状态
      }))

      this.setData({
        videoList,
        currentVideoContext: videoContext
      })
    } else {
      // 只更新视频上下文，不触发setData
      this.setData({
        currentVideoContext: videoContext
      })
    }
  },

  // 视频暂停事件
  onVideoPause(e) {
    const index = e.currentTarget.dataset.index

    // 检查是否需要更新播放状态
    const currentVideo = this.data.videoList[index]
    const needsUpdate = currentVideo.isPlaying
    
    if (needsUpdate) {
      // 更新播放状态
      const videoList = this.data.videoList.map((video, idx) => ({
        ...video,
        isPlaying: idx === index ? false : video.isPlaying
      }))

      this.setData({ videoList })
    }
  },

  // 视频结束事件
  onVideoEnd(e) {
    const index = e.currentTarget.dataset.index

    // 自动播放下一个视频
    if (index < this.data.videoList.length - 1) {
      setTimeout(() => {
        // 使用swiper组件切换到下一个视频，这样会自动触发onSwiperChange事件
        const query = wx.createSelectorQuery()
        query.select('.video-swiper').context(res => {
          if (res && res.context) {
            res.context.current = index + 1
          }
        }).exec()
        
        // 备用方案：直接设置currentIndex触发swiper切换
        this.setData({ currentIndex: index + 1 })
      }, 500)
    }
  },

  // 跳转到指定视频
  jumpToVideo(e) {
    const targetIndex = parseInt(e.currentTarget.dataset.index)
    const currentIndex = this.data.currentIndex

    if (targetIndex !== currentIndex) {
      // 使用swiper组件切换，这样会自动触发onSwiperChange事件处理所有逻辑
      this.setData({ currentIndex: targetIndex })
    }
  },

  // 发布视频
  onPublishVideo(e) {
    const index = e.currentTarget.dataset.index
    const video = this.data.videoList[index]
    
    // 跳转到上传页面
    wx.navigateTo({
      url: '/pages/upload/upload'
    })
  },

  // 分享给好友
  onShareToFriend(e) {
    const index = e.currentTarget.dataset.index
    const video = this.data.videoList[index]
    
    // 直接触发分享给好友
    wx.showShareMenu({
      withShareTicket: true,
      menus: ['shareAppMessage']
    })
    
    wx.showToast({
      title: '请点击右上角分享给好友',
      icon: 'none'
    })
  },

  // 分享给群
  onShareToGroup(e) {
    const index = e.currentTarget.dataset.index
    const video = this.data.videoList[index]
    
    // 直接触发分享给群
    wx.showShareMenu({
      withShareTicket: true,
      menus: ['shareAppMessage']
    })
    
    wx.showToast({
       title: '请点击右上角分享给群',
       icon: 'none'
     })
   },

  // 分享
  onShare(e) {
    const index = e.currentTarget.dataset.index
    const video = this.data.videoList[index]

    // 显示分享选项
    // 官方文档: https://developers.weixin.qq.com/miniprogram/dev/api/ui/interaction/wx.showActionSheet.html
    wx.showActionSheet({
      itemList: ['分享给朋友', '分享到朋友圈', '生成分享卡片'],
      success: (res) => {
        switch (res.tapIndex) {
          case 0:
            // 分享给朋友
            this.shareToFriend(video)
            break
          case 1:
            // 分享到朋友圈
            this.shareToTimeline(video)
            break
          case 2:
            // 生成分享卡片
            this.generateShareCard(video)
            break
        }
      }
    })
  },

  // 分享给朋友
  shareToFriend(video) {
    wx.showShareMenu({
      withShareTicket: true,
      menus: ['shareAppMessage']
    })

    // 官方文档: https://developers.weixin.qq.com/miniprogram/dev/api/ui/interaction/wx.showToast.html
    wx.showToast({
      title: '请点击右上角分享',
      icon: 'none'
    })
  },

  // 分享到朋友圈
  shareToTimeline(video) {
    wx.showShareMenu({
      withShareTicket: true,
      menus: ['shareTimeline']
    })

    // 官方文档: https://developers.weixin.qq.com/miniprogram/dev/api/ui/interaction/wx.showToast.html
    wx.showToast({
      title: '请点击右上角分享到朋友圈',
      icon: 'none'
    })
  },

  // 生成分享卡片
  generateShareCard(video) {
    // 官方文档: https://developers.weixin.qq.com/miniprogram/dev/api/ui/interaction/wx.showToast.html
    wx.showToast({
      title: '正在生成分享卡片...',
      icon: 'loading',
      duration: 2000
    })

    // 模拟生成分享卡片
    setTimeout(() => {
      // 官方文档: https://developers.weixin.qq.com/miniprogram/dev/api/ui/interaction/wx.showToast.html
      wx.showToast({
        title: '分享卡片已生成',
        icon: 'success'
      })
    }, 2000)
  },

  // 页面分享配置
  onShareAppMessage(options) {
    const currentVideo = this.data.videoList[this.data.currentIndex]
    console.log('分享视频:', currentVideo)
    return {
      title: currentVideo ? currentVideo.title : '精彩视频分享',
      path: `/pages/video-detail/video-detail?id=${currentVideo ? currentVideo.id : ''}`,
      imageUrl: currentVideo ? currentVideo.cover : '/images/placeholder.png'
    }
  },

  // 分享到朋友圈配置
  onShareTimeline(options) {
    const currentVideo = this.data.videoList[this.data.currentIndex]
    return {
      title: currentVideo.title,
      imageUrl: currentVideo.cover
    }
  },

  // 页面显示时
  onShow() {
    // 恢复当前视频播放
    setTimeout(() => {
      this.playCurrentVideo()
    }, 300)
  },

  // 页面隐藏时
  onHide() {
    // 暂停所有视频
    this.data.videoList.forEach((video, index) => {
      this.stopVideo(index)
    })
  },

  // 页面卸载时
  onUnload() {
    // 清理所有视频资源
    this.data.videoList.forEach((video, index) => {
      this.stopVideo(index)
    })


  },

  // 音量控制开始
  onVolumeStart(e) {
    this.setData({
      touchStartY: e.touches[0].clientY,
      showVolumeIndicator: true
    })
  },

  // 音量控制移动
  onVolumeMove(e) {
    const currentY = e.touches[0].clientY
    const deltaY = this.data.touchStartY - currentY
    const sensitivity = 2 // 调节灵敏度

    let newVolume = this.data.volumePercent + (deltaY / sensitivity)
    newVolume = Math.max(0, Math.min(100, newVolume))

    this.setData({
      volumePercent: newVolume,
      touchStartY: currentY
    })

    // 设置视频音量
    const videoContext = this.data.currentVideoContext
    if (videoContext) {
      videoContext.setVolume(newVolume / 100)
    }
  },

  // 音量控制结束
  onVolumeEnd(e) {
    setTimeout(() => {
      this.setData({
        showVolumeIndicator: false
      })
    }, 1000)
  },

  // 切换关注状态
  toggleFollow(e) {
    const index = e.currentTarget.dataset.index
    const videoList = this.data.videoList
    const video = videoList[index]
    
    if (!video) return
    
    // 切换关注状态
    video.isFollowed = !video.isFollowed
    
    // 更新视频列表
    this.setData({
      videoList: videoList
    })
    
    // 这里可以添加API调用来同步关注状态到服务器
    console.log(`${video.isFollowed ? '关注' : '取消关注'}了用户: ${video.author_nickname}`)
  },

  // 切换静音状态
  toggleMute(e) {
    const index = e.currentTarget.dataset.index
    const videoList = this.data.videoList
    const video = videoList[index]
    
    if (!video) return
    
    // 切换静音状态
    video.isMuted = !video.isMuted
    
    // 更新视频列表
    this.setData({
      videoList: videoList
    })
    
    // 设置视频音量
    const videoContext = this.data.currentVideoContext
    if (videoContext) {
      if (video.isMuted) {
        videoContext.setVolume(0)
      } else {
        videoContext.setVolume(this.data.volumePercent / 100)
      }
    }
    
    console.log(`视频${video.isMuted ? '已静音' : '已取消静音'}`)
  },

  // 初始化关注状态（可以从本地存储或API获取）
  initFollowStatus() {
    // 这里可以从本地存储或API获取用户的关注列表
    // 暂时使用随机状态作为示例
    const videoList = this.data.videoList.map(video => ({
      ...video,
      isFollowed: Math.random() > 0.7 // 30%的概率已关注
    }))
    
    this.setData({
      videoList: videoList
    })
  }

})